package mqpaydemo.paydemo.pay.portal.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import mqpaydemo.paydemo.pay.api.MoneyService;
import mqpaydemo.paydemo.pay.api.OrdersService;
import mqpaydemo.paydemo.pay.orm.entity.Money;
import mqpaydemo.paydemo.pay.portal.rabbitMq.PaySend;
import mqpaydemo.paydemo.pay.request.OrdersRequest;
import mqpaydemo.paydemo.pay.response.Result;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.math.BigDecimal;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author ljs
 * @since 2021-09-10
 */
@Controller
@RequestMapping("/pay/order")
public class OrdersController {
    @Resource
     OrdersService OrdersService;
    @Resource
    MoneyService moneyService;
    @Resource
    PaySend paySend;
    @RequestMapping("/toPay")
    public String topay() {
        return "toPay";
    }
    @ResponseBody
    @PostMapping("/pay")
    public Result<Boolean> pay(OrdersRequest OrdersRequest){
        Boolean bln=false;
        //要先判断当前用户的余额是不是大于下单的价格
        //查找用户现在的余额
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("uid",OrdersRequest.getUserId());
        Money money=moneyService.getOne(queryWrapper);
        BigDecimal uprice=null;
        if(money!=null){
            uprice=  money.getAmount();
        }
        if(uprice!=null){
            //比较大小
           //-1 小于
            //0  等于
            //1  大于
            if(uprice.compareTo(OrdersRequest.getPrice())==-1){
                return Result.ofFailMsg("余额不足");
            }
        }
        Result<Boolean> result=     OrdersService.pay(OrdersRequest);
         bln=result.getData();
        if (bln){
            //发送mq
            paySend.send(OrdersRequest);
        }
        return Result.ofSuccess(bln);
    }

}